<?php

namespace App\Http\Controllers\admin;

use App\model\AddShop;
use App\Model\ShopAttrTypeModel;
use App\Model\SkuModel;
use App\Sku;
use Validator;
use App\Model\QandaGood;
use App\Model\QandaModel;
use App\Model\SourceModel;
use App\Model\ShopGoodType;
use App\Model\ShopSourcePic;
use App\Model\ShopTypeModel;
use App\Model\ShopGoodModel;
use App\Model\ShopBrandModel;
use App\Model\ShopLabelModel;
use App\Model\StoreGoodModel;
use App\Model\AdminLogsModel;

use App\Model\ShopGoodPicModel;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;



//主页
class ShopController extends Controller
{
	// index页
	public function index(Request $request)
	{
		$sort = $request->input('sort',3);
		$state = $request->input('state',1);
		if(empty(request()->sort)){
			$sort = 3;
		}
		if(empty(request()->state)){
			$state = 1;
		}
		$list = ShopGoodModel::from('shop_good as s')
			->leftjoin('add_shop as g','s.gid','=','g.id')
			->select('s.*','g.status')
			->where('g.status','<>',2)
			->where(function ($query) {
			if (request()->keywords) {
				$query->where('s.name', 'like', "%" . request()->keywords . "%");
			}
			if (request()->title) {
				$query->where('s.title', 'like', "%" . request()->title . "%");
			}
			if(request()->gid){
				$query->where('s.gid', request()->gid);
			}
			if(request()->id){
				$query->where('s.id', request()->id);
			}
			if(request()->num == 1){
				$query->where('s.num', 0);
			}
			if(request()->num == 2){
				$query->where('s.num','<>', 0);
			}

			if (request()->month) {
				$month_arr = explode("~", request()->month);
				$mintime = $month_arr[0];
				$maxtime = $month_arr[1] . " 23:59:59";
				$query->whereBetween('s.created_at', [$mintime, $maxtime]);
			}

			if(request()->label){
				$lid = ShopLabelModel::where('name',request()->label)->value('id');
				$query->where('labels','like','%,'.$lid.',%');
			}

			if(request()->type){
				$gids = ShopGoodType::where('tid',request()->type)->get();
				$ids = '';
				if($gids) {
					foreach ($gids as $k => $v) {
						$ids .= $v['gid'] . ",";
					}
					$ids = explode(',', trim($ids, ','));
					$query->whereIn('id', $ids);
				}
			}

			if(request()->brand){
				$query->where('s.bid',request()->brand);
			}


			if(request()->sell){
				$query->where('s.is_sell',request()->sell);
			}
		})
			->when($state, function ($query) use ($state){
				return $query->where('s.state',$state);
			})
			->when($sort, function ($query) use ($sort){
				if($sort == 1){
					return $query->orderBy('id','asc');
				}elseif($sort == 2){
					return $query->orderBy('id','desc');
				}elseif($sort == 3){
					return $query->OrderBy(DB::raw('convert(`s`.`name` using gbk)'));
				}
			})
//			->orderBy('id', 'desc')
//			->orderBy("sort", 'desc')
//			->where('state', '<>', 3)
//				->where('state',1)
			->paginate(10);
		foreach ($list as $k => $v) {
			$list[$k]['tname'] = '';
			$type = ShopGoodType::where('gid', $v['id'])->select('tid')->get();
			$tid = '';
			foreach ($type as $key => $val) {
				$tid .= $val['tid'] . ",";
			}
			if ($tid != '') {
				$tname = '';
				$tids = explode(',', trim($tid, ','));

				foreach ($tids as $j => $i) {
					$tname .= ShopTypeModel::where('tid', $i)->value('name') . ",";
				}

				$list[$k]['tname'] = $tname;
			}
			$list[$k]['bname'] = '';
			if ($v['bid']) {
				$list[$k]['bname'] = ShopBrandModel::where('bid', $v['bid'])->value('name');
			}
//			if (!$v['picname']) {
//				$list[$k]['picname'] = "http://" . $_SERVER['HTTP_HOST'] . "/img/good.png";
//			} else {
//				$list[$k]['picname'] = "http://" . $_SERVER['HTTP_HOST'] . $v['picpath'] . $v['picname'];
//			}
			if($v->oss_pic){
				$v->picname = $v->oss_pic;
			}else{
				if($v->picname){
					$v->picname = 'http://'.$_SERVER['HTTP_HOST'].$v->picpath.$v->picname;
				}else{
					$v->picname = "http://".$_SERVER['HTTP_HOST']."/img/good.png";
				}
			}

			$list[$k]['other_num'] = ShopGoodPicModel::where('gid',$v['id'])->count();
			$list[$k]['pic_num'] = SourceModel::where('gid',$v['id'])->where('type',1)->count();
			$list[$k]['vedio_num'] = SourceModel::where('gid',$v['id'])->where('type',2)->count();
			$list[$k]['qanda_num'] = QandaGood::where('gid',$v['id'])->count();
			$list[$k]['s_state'] = AddShop::where('id',$v['gid'])->value('status');
			$list[$k]['img_arr'] = ShopGoodPicModel::where('gid',$v['id'])->get();
			foreach($list[$k]['img_arr'] as $key=>$val){
				if($val['oss_pic']){
					$val['picname'] = $val['oss_pic'];
				}else{
					$val['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$val['picname'];
				}
			}
		}
		//类别(搜索)
		$sql = "SELECT * FROM `shop_type` ORDER BY concat(path,id),sort desc";
		$all_list = DB::select($sql);

		//品牌
		$brand = ShopBrandModel::OrderBy(DB::raw('convert(`head` using gbk)'))->get();

		$sub_cy['keywords'] = request()->keywords;
		$sub_cy['month'] = request()->month;
		$sub_cy['label'] = request()->label;
		$sub_cy['type'] = request()->type;
		$sub_cy['brand'] = request()->brand;
		$sub_cy['state'] = request()->state;
		$sub_cy['sell'] = request()->sell;
		$sub_cy['title'] = request()->title;
		$sub_cy['sort'] = request()->sort;
		$sub_cy['num'] = request()->num;
		$page = $list->appends($sub_cy)->links();
		$pages = $request->input('page',1);

		return view('admin.shop.index', compact('list', 'page', 'request','pages','all_list','brand'));
	}

	public function index_two(Request $request)
	{
		$sort = $request->input('sort',1);
		$list = ShopGoodModel::where(function ($query) {
			if (request()->keywords) {
				$query->where('name', 'like', "%" . request()->keywords . "%");
			}
			if (request()->title) {
				$query->where('title', 'like', "%" . request()->title . "%");
			}

			if (request()->month) {
				$month_arr = explode("~", request()->month);
				$mintime = $month_arr[0];
				$maxtime = $month_arr[1] . " 23:59:59";
				$query->whereBetween('created_at', [$mintime, $maxtime]);
			}

			if(request()->label){
				$lid = ShopLabelModel::where('name',request()->label)->value('id');
				$query->where('labels','like','%,'.$lid.',%');
			}

			if(request()->type){
				$gids = ShopGoodType::where('tid',request()->type)->get();
				$ids = '';
				if($gids) {
					foreach ($gids as $k => $v) {
						$ids .= $v['gid'] . ",";
					}
					$ids = explode(',', trim($ids, ','));
					$query->whereIn('id', $ids);
				}
			}

			if(request()->brand){
				$query->where('bid',request()->brand);
			}

			if(request()->state){
				$query->where('state',request()->state);
			}
			if(request()->sell){
				$query->where('is_sell',request()->sell);
			}
		})

//			->orderBy('id', 'desc')
			->orderBy(DB::raw('convert(`name` using gbk)'))
//			->orderBy("sort", 'desc')
			->where('state', '<>', 3)
			->paginate(10);
		foreach ($list as $k => $v) {
			$list[$k]['tname'] = '';
			$type = ShopGoodType::where('gid', $v['id'])->select('tid')->get();
			$tid = '';
			foreach ($type as $key => $val) {
				$tid .= $val['tid'] . ",";
			}
			if ($tid != '') {
				$tname = '';
				$tids = explode(',', trim($tid, ','));

				foreach ($tids as $j => $i) {
					$tname .= ShopTypeModel::where('tid', $i)->value('name') . ",";
				}

				$list[$k]['tname'] = $tname;
			}
			$list[$k]['bname'] = '';
			if ($v['bid']) {
				$list[$k]['bname'] = ShopBrandModel::where('bid', $v['bid'])->value('name');
			}
			if (!$v['picname']) {
				$list[$k]['picname'] = "http://" . $_SERVER['HTTP_HOST'] . "/img/good.png";
			} else {
				$list[$k]['picname'] = "http://" . $_SERVER['HTTP_HOST'] . $v['picpath'] . $v['picname'];
			}
		}
		//类别(搜索)
		$sql = "SELECT * FROM `shop_type` ORDER BY concat(path,id),sort desc";
		$all_list = DB::select($sql);

		//品牌
		$brand = ShopBrandModel::OrderBy(DB::raw('convert(`head` using gbk)'))->get();

		$sub_cy['keywords'] = request()->keywords;
		$sub_cy['month'] = request()->month;
		$sub_cy['label'] = request()->label;
		$sub_cy['type'] = request()->type;
		$sub_cy['brand'] = request()->brand;
		$sub_cy['state'] = request()->state;
		$sub_cy['sell'] = request()->sell;
		$sub_cy['title'] = request()->title;
		$page = $list->appends($sub_cy)->links();
		$pages = $request->input('page',1);

		return view('admin.shop.index_two', compact('list', 'page', 'request','pages','all_list','brand'));
	}

	//编辑商品销售标题
	public function update_title(){
		$id = request()->id;
		$title = request()->title;
		$str_user ='/[\'.,:;*?~`!@#$%^&+=)(<>{}]|5261\]|\[|\/|\\\|\"|\|/';
		if(preg_match($str_user,$title)){
			return ['code'=>0,'msg'=>'销售标题不可包含特殊字符'];
		}
		DB::beginTransaction();
		try{
			ShopGoodModel::where('id',$id)->update(['title'=>$title]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'设置失败'];
		}
		return ['code'=>1,'msg'=>'设置成功'];
	}
	//添加商品页
	public function add()
	{
		//类别(搜索)
		$sql = "SELECT * FROM `shop_type` ORDER BY concat(path,tid),id desc";
		$all_list = DB::select($sql);
		//品牌
		$sql2 = "SELECT * FROM `shop_brand` ORDER BY concat(path,id),id desc";
		$all_list2 = DB::select($sql2);

		//规格类型
		$sql3 = "SELECT * FROM `shop_attr_type` ORDER BY id desc";
		$all_list3 = DB::select($sql3);
		foreach ($all_list as $k => $v) {
			$v->is_exit = 0;
			if (ShopTypeModel::where('pid', $v->id)->first()) {
				$v->is_exit = 1;
			}
		}
		foreach ($all_list2 as $k => $v) {
			$v->is_exit = 0;
			if (ShopBrandModel::where('pid', $v->id)->first()) {
				$v->is_exit = 1;
			}
		}
		return view('admin.shop.add', compact('all_list', 'all_list2', 'all_list3'));
	}

	//添加商品
	public function insert(Request $request)
	{
		$post = $request->post();
		$validator = Validator::make($post, [
			'name' => 'required|unique:shop_good,name',
			'cost_price' => 'required',
			'sell_price' => 'required',
			'sort' => 'required|digits_between:1,999',
			'picname' => 'required',
			'contents' => 'required',
		], [
			'name.required' => '商品名不能为空',
			'name.unique' => '该商品已存在',
			'cost_price.unique' => '请输入成本价',
			'sell_price.unique' => '请输入销售价',
			'sort.required' => '请输入排序',
			'sort.digits_between' => '排序应为 1到999 之间',
			'picname.required' => 'Logo不能为空',
			'contents.required' => '请输入商品详情',
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}
		//事物
		DB::beginTransaction();
		try {
			$type = New ShopGoodModel();
			if (request()->tid) {
				$ptype = ShopTypeModel::where('id', request()->tid)->first();
				if (!$ptype) {
					return returnJson(0, '该分类不存在');
				}
			}
			if (request()->is_attr) {
				if (!request()->attrtype_id) {
					return returnJson(0, '请选择规格类型');
				}
			}
			$type->name = request()->name;
			$type->picname = request()->picname;
			$type->oss_pic = request()->picname;
			$type->tid = request()->tid;
			$type->bid = request()->bid;
			$type->is_attr = request()->is_attr;
			$type->attrtype_id = request()->attrtype_id;
			$type->cost_price = request()->cost_price;
			$type->sell_price = request()->sell_price;
			$type->sale_num = request()->sale_num;
			$type->sort = request()->sort;
			$type->content = request()->contents;
			$type->save();

			DB::commit();
		} catch (Exception $e) {
			DB::rollBack();
			throw $e;
			return returnJson(0, '操作失败,请稍后再试');
		}
		return returnJson(1, '添加成功');
	}

	//更改状态
	public function up_state(Request $request, ShopGoodModel $auModel)
	{
		$state = $request->post('state');//状态
		$id = $request->post('id');
		if ($state == 1) {
			$list = ShopGoodModel::where('id', $id)->first();
			if ($list['cost_price'] <= 0) {
				return ['code' => 1, 'msg' => '该商品价格异常'];
			}
		}
		$returnArr = $auModel->updateState($id, $state);
		return response()->json($returnArr);
	}

	//更改心愿单开关
	public function up_wish(Request $request, ShopGoodModel $auModel)
	{
		$is_wish = $request->post('is_wish');//状态
		$id = $request->post('id');
	
		$returnArr = $auModel->updateWish($id, $is_wish);
		return response()->json($returnArr);
	}

	//编辑页面
	public function edit(Request $request)
	{
		//类别(搜索)
		$sql = "SELECT * FROM `shop_type` ORDER BY concat(path,tid),sort desc";
		$all_list = DB::select($sql);

		//品牌
		$sql2 = "SELECT * FROM `shop_brand` ORDER BY concat(path,bid),id desc";
		$all_list2 = DB::select($sql2);

		foreach ($all_list as $k => $v) {
			$v->is_exit = 0;
			if (ShopTypeModel::where('pid', $v->tid)->first()) {
				$v->is_exit = 1;
			}
		}
		foreach ($all_list2 as $k => $v) {
			$v->is_exit = 0;
			if (ShopBrandModel::where('pid', $v->bid)->first()) {
				$v->is_exit = 1;
			}
		}
		//规格类型
//		$sql3 = "SELECT * FROM `shop_attr_type` ORDER BY `tname` using gbk desc";
//		$all_list3 = DB::select($sql3);
		$all_list3 = ShopAttrTypeModel::orderBy(DB::raw('convert(`tname` using gbk)'))->get();

		$list = ShopGoodModel::where('id', request()->id)->first();
//		if (!$list->picname) {
//			$list->picname = "http://" . $_SERVER['HTTP_HOST'] . "/img/good.png";
//			$list->oldname = "";
//		} else {
//			$list->oldname = $list->picname;
//			$list->picname = "http://" . $_SERVER['HTTP_HOST'] . $list->picpath . $list->picname;
//
//		}
		if($list->oss_pic){
			$list->picname = $list->oss_pic;
			$list->oldname = $list->oss_pic;
		}else{
			if($list->picname){
				$list->oldname = $list->picname;
				$list->picname = 'http://'.$_SERVER['HTTP_HOST'].$list->picpath.$list->picname;
			}else{
				$list->picname = "http://".$_SERVER['HTTP_HOST']."/img/good.png";
				$list->oldname = "";
			}
		}
		return view('admin.shop.edit', compact('list', 'all_list', 'all_list2', 'all_list3', 'request'));
	}

	//编辑商品
	public function update(Request $request)
	{
		$post = $request->post();
		$validator = Validator::make($post, [
			'name' => 'required',
			'cost_price' => 'required',
			'sell_price' => 'required',
			'sort' => 'required|digits_between:1,999',
//			'picname' => 'required',
			'contents' => 'required',
		], [
			'name.required' => '商品名不能为空',
			'cost_price.unique' => '请输入成本价',
			'sell_price.unique' => '请输入销售价',
			'sort.required' => '请输入排序',
			'sort.digits_between' => '排序应为 1到999 之间',
//			'picname.required' => 'Logo不能为空',
			'contents.required' => '请输入商品详情',
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}
		if (request()->tid) {
			$ptype = ShopTypeModel::where('id', request()->tid)->first();
			if (!$ptype) {
				return returnJson(0, '该分类不存在');
			}
		}
		if (request()->is_attr) {
			if (!request()->attrtype_id) {
				return returnJson(0, '请选择规格类型');
			}
		}

		if (ShopGoodModel::where('id', $post['id'])->update(
			[
				"name" => request()->name,
				// "picname" => request()->picname,
				// 'oss_pic' => request()->picname,
//				'tid' => request()->tid,
				'bid' => request()->bid,
				'is_attr' => request()->is_attr,
				'attrtype_id' => request()->attrtype_id,
				"sort" => request()->sort,
				'cost_price' => request()->cost_price,
				'sell_price' => request()->sell_price,
				'sale_num' => request()->sale_num,
				'content' => request()->contents,
			]
		)) {
			$msg = '编辑商品【'.request()->name.'】id('.$post['id'].')';
			AdminLogsModel::addLog($msg);
			return returnJson(1, '更改成功');
		} else {
			return returnJson(0, '更改失败');
		}
	}

	//删除商品
	public function del()
	{
		$id = request()->id;

		if (StoreGoodModel::where('gid', $id)->first()) {
			return returnJson(1, '云仓库含有该商品,不可删除');
		}
		DB::beginTransaction();
		try{
			//查询商品信息
			$list = ShopGoodModel::where('id',$id)->first();
			//货源后台的商品
			$store_list = AddShop::where('id',$list['gid'])->first();
			if($store_list){
				AddShop::where('id',$list['gid'])->update(['status'=>4]);
			}
			//删除商品
			ShopGoodModel::where('id', $id)->update(['state' => 3]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return returnJson(0, '删除失败');
		}
		return returnJson(1, '删除成功');
	}

	//编辑排序
	public function sorts_paixu(){
		$id = request()->id;
		$paixu = request()->paixu;
		//编辑商品的排序
		DB::beginTransaction();
		try{
			//查询商品信息
			$list = ShopGoodModel::where('id',$id)->first();
			if(!$list){
				return ['code'=>0,'msg'=>'该商品信息有误']; 
			}
			ShopGoodModel::where('id',$id)->update(['sort'=>$paixu]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return returnJson(0, '设置失败');
		}
		return returnJson(1, '设置成功');
	}

	//更改状态
	public function edit_state()
	{
		DB::beginTransaction();
		try {
			$state = ['1'=>'专卖商品','2'=>'非专卖商品'];
			$good = ShopGoodModel::where('id',request()->id)->first();
			ShopGoodModel::where('id', request()->id)->update(['is_sell' => request()->state]);
			DB::commit();
			$msg = '将商品【'.$good['name'].'】id('.$good['id'].')更改为'.$state[request()->state];
			AdminLogsModel::addLog($msg);
			return ['code' => 1, 'msg' => '更改成功'];
		} catch (Exception $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => '更改失败'];
		}
	}

	//查看其他主图
	public function pic_other(Request $request)
	{
		$id = $request->input('id');
		$gname = ShopGoodModel::where('id', $id)->value('name');
		$list = ShopGoodPicModel::where('gid', $id)->get();
		return view('admin.shop.good_pic', compact('list', 'gname', 'id', 'request'));

	}

	//添加其他图片
	public function pic_add()
	{
		if (!request()->picname) {
			return ['code' => 0, 'msg' => '请上传图片'];
		}

		DB::beginTransaction();
		try {
			$list = ShopGoodModel::where('id',request()->gid)->first();
			$picname = trim(request()->picname, ',');
			$picname = explode(',', $picname);
			foreach ($picname as $k => $v) {
				ShopGoodPicModel::create([
					'gid' => request()->gid,
					'picname' => $v,
					'oss_pic' => $v,
					'type' => 1,
				]);
			}

			DB::commit();
			$msg = '商品【'.$list['name'].'】(id:'.$list['id'].'),增加其余主图';
			AdminLogsModel::addLog($msg);
			return ['code' => '1', 'msg' => '上传成功'];
		} catch (Exception $e) {
			DB::rollBack();
			return ['code' => '0', 'msg' => '上传失败'];
		}
	}

	//删除图片
	public function pic_del()
	{
		$pic = ShopGoodPicModel::where('id', request()->id)->first();
		if (!$pic) {
			return ['code' => '0', 'msg' => '该图片不存在'];
		}
		DB::beginTransaction();
		try {
//			@unlink("." . $pic['picname']);
			ShopGoodPicModel::where('id', request()->id)->delete();
			DB::commit();
			$list = ShopGoodModel::where('id',$pic['gid'])->first();
			$msg = '商品【'.$list['name'].'】(id:'.$list['id'].'),删除其余主图';
			AdminLogsModel::addLog($msg);
			return ['code' => 1, 'msg' => "删除成功"];
		} catch (Exception $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => '删除失败'];
		}
	}


	public function label(Request $request, ShopLabelModel $label)
	{
		$label_list = $label->where('state', '1')->get();

		$good_id = $request->id;
		$good = ShopGoodModel::where('id', $good_id)->first();

		$yxz_label = explode(',', rtrim($good->labels, ','));

		return view('admin.shop.label')
			->with('label_list', $label_list)
			->with('yxz_label', $yxz_label)
			->with('good', $good);
	}

	public function label_update(Request $request)
	{
		if (!$request->filled('id')) {
			return returnJson(0, '参数错误');
		}
		$id = $request->post('id');
		$label = $request->label;

		$str = ",";
		$str_name = '';
		if (!empty($label)) {
			foreach ($label as $v) {
				$str .= $v . ',';
				$str_name .= ShopLabelModel::where('id',$v)->value('name').",";
			}

		} else {
			$str = '';
			$str_name = '';
		}

		DB::beginTransaction();
		try {
			$list = ShopGoodModel::where('id',$id)->first();
			ShopGoodModel::where('id', $id)->update(['labels' => $str]);
			$msg = '商品【'.$list['name'].'】设置标签('.trim($str_name,',').')';
			AdminLogsModel::addLog($msg);
			DB::commit();
		} catch (Exception $e) {
			DB::rollBack();
			throw $e;
			return returnJson(0, '操作失败,请稍后再试');
		}

		return returnJson(1, '操作成功');
	}

	//问答库
	public function q_a_store(Request $request)
	{
		// $list = QandaModel::where(function ($query) {
		// 	if (request()->keywords) {
		// 		$query->where('question', 'like', "%" . request()->keywords . "%");
		// 	}
		// 	if(request()->gid){
		// 		$aids = QandaGood::where('gid',request()->gid)->get();
		// 		$aa = '';
		// 		foreach($aids as $k=>$v){
		// 			$aa .= $v['qid'].',';
		// 		}
		// 		$aa_cy = explode(',',trim($aa,','));
		// 		$query->whereIn('id',$aa_cy);
		// 	}
		// })
		// 	->orderBy('id', 'desc')
		// 	->paginate(10);
		
		$list = DB::table('qanda_good')
		->leftjoin('shop_qanda','qanda_good.qid','shop_qanda.id')
		->leftjoin('shop_good','shop_good.id','qanda_good.gid')
		->where(function ($query) {
			if (request()->keywords) {
				$query->where('shop_qanda.question', 'like', "%" . request()->keywords . "%");
			}
			if(request()->gid){
				$aids = QandaGood::where('gid',request()->gid)->get();
				$aa = '';
				foreach($aids as $k=>$v){
					$aa .= $v['qid'].',';
				}
				$aa_cy = explode(',',trim($aa,','));
				$query->whereIn('shop_qanda.id',$aa_cy);
			}
			if(request()->is_exit){
				if(request()->is_exit == 1){
					$query->where('shop_good.state','3');
				}elseif(request()->is_exit == 2){
					$query->where('shop_good.state','<>','3');
				}
			}
		})
		->select('shop_qanda.*')
		->orderBy('shop_qanda.id','desc')
		->paginate(15);
		
		foreach($list as $k=>$v){
			$gid = QandaGood::where('qid',$v->id)->value('gid');
			$good = ShopGoodModel::where('id',$gid)->first();
			if($good){
				$v->gid = $good['id'];
				$v->gname = $good['name'];
			}

		}

		$pageParam['keywords'] = request()->keywords;
		$pageParam['is_exit'] = request()->is_exit;
		//分页
		$page = $list->appends($pageParam)->links();

		return view('admin.qanda.index', compact('list', 'page', 'request'));
	}

	//问答库-添加
	public function add_q()
	{
		return view('admin.qanda.add');
	}

	//问答库-添加
	public function insert_q(Request $request)
	{
		$post = $request->post();
		$validator = Validator::make($post, [
			'question' => 'required',
			'answer' => 'required',
		], [
			'question.required' => '请输入问题',
			'answer.required' => '请输入答案',
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}
		DB::beginTransaction();
		try {

			$list = QandaModel::create([
				'question' => request()->question,
				'answer' => request()->answer,
			]);
			$msg = '增加问答信息【'.request()->question.'】(id:'.$list['id'].')';
			AdminLogsModel::addLog($msg);
			DB::commit();
			return returnJson(1, '添加成功');
		} catch (Exception $e) {
			DB::rollBack();
			return returnJson(0, '添加失败');
		}
	}

	//问答库-编辑
	public function edit_q()
	{
		if (!request()->id) {
			return returnJson(0, '非法入侵');
		}
		$list = QandaModel::where('id', request()->id)->first();
		return view('admin.qanda.edit', compact('list'));
	}

	//问答库-编辑
	public function update_q(Request $request)
	{
		$post = $request->post();
		$validator = Validator::make($post, [
			'question' => 'required',
			'answer' => 'required',
		], [
			'question.required' => '请输入问题',
			'answer.required' => '请输入答案',
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}
		if (QandaModel::where('id', '<>', request()->id)->where('question', request()->question)->first()) {
			return returnJson(0, '该问题已存在');
		}
		DB::beginTransaction();
		try {
			QandaModel::where('id', request()->id)->update([
				'question' => request()->question,
				'answer' => request()->answer,
			]);
			DB::commit();
			$msg = '编辑问答信息【'.request()->question.'】(id:'.request()->id.')';
			AdminLogsModel::addLog($msg);
			return returnJson(1, '编辑成功');
		} catch (Exception $e) {
			DB::rollBack();
			return returnJson(0, '编辑失败');
		}
	}

	//删除问答
	public function delete_q()
	{
		if (!request()->id) {
			return returnJson(0, '非法入侵');
		}
		DB::beginTransaction();
		try {
			$question = QandaModel::where('id',request()->id)->value('question');
			QandaModel::where('id', request()->id)->delete();
			DB::commit();
			$msg = '删除问答信息【'.$question.'】(id:'.request()->id.')';
			AdminLogsModel::addLog($msg);
			return returnJson(1, '已删除');
		} catch (Exception $e) {
			DB::rollBack();
			return returnJson(0, '删除失败');
		}
	}

	//素材库
	public function source(Request $request)
	{
		$type = $request->input('types', 1);
		$id = request()->id;
		$list_pic = SourceModel::where('gid', $id)->where('type', 1)->orderBy('id', 'desc')->get();
		$list_vedio = SourceModel::where('gid', $id)->where('type', 2)->orderBy('id', 'desc')->get();
		$list_qanda = QandaGood::where('gid', $id)->orderBy('created_at', 'desc')->get();
		$qanda = [];
		foreach($list_qanda as $k=>$v){
			//问答信息
			$qanda_res = QandaModel::where('id',$v['qid'])->first();
			$qanda[$k]['id'] = $qanda_res['id'];
			$qanda[$k]['question'] = $qanda_res['question'];
			$qanda[$k]['answer'] = $qanda_res['answer'];
			$qanda[$k]['created_at'] = $qanda_res['created_at'];
		}
		//商品名
		$gname = ShopGoodModel::where('id', $id)->value('name');
		foreach($list_pic as $key=>$val){
			$pics = ShopSourcePic::where('sid',$val->id)->first();
			if($pics['oss_pic']){
				$list_pic[$key]['picname'] = $pics['oss_pic'];
			}else{
				$list_pic[$key]['picname'] = $pics['picname'];
			}
		}
		return view('admin.shop.source', compact('list_pic', 'list_vedio', 'id', 'type', 'request', 'gname','qanda'));
	}
	//其余主图
	public function source_other(Request $request){
		//素材图片ID
		$id = request()->id;
		//获取商品ID
		$source = SourceModel::where('id',$id)->first();
		$gid = $source['gid'];
		$sname = $source['title'];
		//获取商品名
		$gname = ShopGoodModel::where('id',$gid)->value('name');
		$list = ShopSourcePic::where('sid',$id)->get();

		return view('admin.shop.source_pic',compact('list','gname','request','sname','id','gid'));
	}

	//删除素材库图片
	public function sourpic_del(){
		DB::beginTransaction();
		try{
			$id = request()->id;
			$list = ShopSourcePic::where('id',$id)->first();
			@unlink(".".$list['picname']);
			ShopSourcePic::where('id',$id)->delete();
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'删除成功'];
	}

	//添加素材
	public function source_add(Request $request)
	{
		$id = request()->id;
		return view('admin.shop.source_add', compact('id','request'));
	}

	//编辑
	public function source_edit(Request $request){
		$id = request()->id;
		$list = SourceModel::where('id',$id)->first();
		return view('admin.shop.source_update',compact('id','request','list'));
	}

	//添加
	public function source_insert()
	{
		DB::beginTransaction();
		try {
			switch (request()->type) {
				case '1':
//					if (!request()->title) {
//						return ['code' => 0, 'msg' => '请输入标题'];
//					}
					if (!request()->contents) {
						return ['code' => 0, 'msg' => '请输入图文详情'];
					}
//					if (!request()->pics) {
//						return ['code' => 0, 'msg'=>'请上传图片'];
//					}
					$picname = explode(',', trim(request()->pics, ','));

					$source = SourceModel::create([
						'gid' => request()->id,
//						'title' => request()->title,
						'content' => request()->contents,
						'type' => 1,
					]);
					foreach ($picname as $key => $val) {
						if($val){
							ShopSourcePic::create([
								'sid' => $source->id,
								'picname' => $val,
								'oss_pic' => $val,
							]);
						}

					}


					break;
				case '2':
					if (!request()->titles) {
						return ['code' => 0, 'msg' => '请输入标题'];
					}
					if (!request()->picname) {
						return ['code' => 0, 'msg' => '请上传封面图'];
					}
					if (!request()->vedio) {
						return ['code' => 0, 'msg' => "请上传视频"];
					}
					SourceModel::create([
						'gid' => request()->id,
						'title' => request()->titles,
						'vedio' => request()->vedio,
						'picname' => request()->picname,
						'oss_pic' => request()->picname,
						'type' => 2,
					]);
					break;
				case '3':
					if (!request()->qid) {
						return ['code' => 0, 'msg' => '请输入问答ID'];
					}
					if (!QandaModel::where('id', request()->qid)->first()) {
						return ['code' => 0, 'msg' => '该问答不存在'];
					}
					SourceModel::create([
						'gid' => request()->id,
						'qid' => request()->qid,
						'type' => 3,
					]);
					break;
			}
			DB::commit();
			$gname = ShopGoodModel::where('id',request()->id)->value('name');
			$msg = '商品【'.$gname.'】添加素材';
			AdminLogsModel::addLog($msg);
			return ['code' => 1, 'msg' => '添加成功', 'data' => request()->type];
		} catch (Exception $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => '添加失败'];
		}
	}

	//删除素材库
	public function source_del()
	{
		$source = SourceModel::where('id', request()->id)->first();
		if (!$source) {
			return ['code' => 0, 'msg' => '非法入侵'];
		}
		//删除
		DB::beginTransaction();
		try {
			if ($source->type == 1) {
				@unlink("." . $source['picname']);
			} elseif ($source->type == 2) {
				@unlink("." . $source['vedio']);
			}
			SourceModel::where('id', request()->id)->delete();
			DB::commit();
			$gname = ShopGoodModel::where('id',$source->gid)->value('name');
			$msg = '商品【'.$gname.'】刪除素材';
			AdminLogsModel::addLog($msg);
			return ['code' => 1, 'msg' => '删除成功'];
		} catch (Exception $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => '删除失败'];
		}
	}

	//删除问答
	public function delete_qanda(){
		//问答ID
		$id = request()->id;
		DB::beginTransaction();
		try{
			//删除问答信息
			QandaModel::where('id',$id)->delete();
			//删除问答商品关联表
			QandaGood::where('qid',$id)->delete();
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'删除失败'];
		}
		return ['code'=>1,'msg'=>'删除成功'];
	}

	//上传视频
	public function source_ve()
	{
		$myfile = $_FILES["file"];
		$tmp = $myfile['tmp_name'];
		$cy_a = time() . '.mp4';
		$a = 'upload/source/' . time() . '.mp4';
		$path = base_path() . '/public/' . $a;

		if (!move_uploaded_file($tmp, $path)) die('视频上传失败');

		$path = "/upload/source/" . time() . '.mp4';
		return ['code' => 1, 'msg' => '上传成功', 'data' => $path, 'data_cy' => $cy_a];
	}

	//编辑素材库多张图片
	public function sourcepic_add(){
		DB::beginTransaction();
		try{
			$id = request()->id;
			if(!request()->picname){
				return ['code'=>0,'msg'=>'请上传图片'];
			}
			$picname = trim(request()->picname,',');
			$picname = explode(',',$picname);
			foreach($picname as $k=>$v){
				ShopSourcePic::create([
					'sid' => $id,
					'picname' => $v,
					'occ_pic' => $v,
				]);
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>'0','msg'=>'操作失败'];
		}
		return ['code'=>'1','msg'=>'操作成功'];
	}

	//编辑商品主图
	public function edit_mpic(){
		$id = request()->id;
		$list = ShopGoodModel::where('id',$id)->first();
		if($list->oss_pic){
			$list->oldname = $list->oss_pic;
			$list->picname = $list->oss_pic;
		}else{
			if($list->picname){
				$list->oldname = $list->picname;
				$list->picname = "http://".$_SERVER['HTTP_HOST'].$list->picpath.$list->picname;
			}else{
				$list->olcname = "";
				$list->picname = "http://".$_SERVER['HTTP_HOST']."/img/good.png";
			}
		}

		return view('admin.shop.edit_mpic',compact('id','list'));
	}

	//编辑商品主图
	public function update_mpic(){
		$id = request()->id;
		$good = ShopGoodModel::where('id',$id)->first();
		DB::beginTransaction();
		try{
			ShopGoodModel::where('id',$id)->update([
				'picname' => request()->picname,
				'oss_pic' => request()->picname,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		$msg = '商品【'.$good['name'].'】编辑主图';
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'上传成功'];
	}

	//编辑
	public function source_update(){
		$title = request()->title;
		$content = request()->contents;
		DB::beginTransaction();
		try{
			SourceModel::where('id',request()->id)->update([
				'title' => $title,
				'content' => $content,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'编辑成功'];
	}

	//问答库-商品添加页
	public function qanda_add(Request $request){

		//商品ID
		$id = request()->id;
		//商品信息
		$gname = ShopGoodModel::where('id',$id)->value('name');
		//该商品相关联的问答
		$list = QandaGood::where('gid',$id)->get();

		$data = [];
		foreach($list as $k=>$v){
			$qanda = QandaModel::where('id',$v['qid'])->first();
			if(!$qanda){
				continue;
			}
			$data[$k]['id'] = $v['qid'];
			$data[$k]['question'] = $qanda['question'];
		}

		//商品未关联的其他问答
		$ids = '';
		foreach($list as $key=>$val){
			$ids .= $val['qid'].",";
		}

		$res = QandaModel::whereNotIn('id',explode(',',trim($ids,',')))->get();
		return view('admin.shop.qanda_add',compact('id','data','res','gname','request'));
	}

	//问答库-添加
	public function qanda_insert(){
		$gid = request()->gid;
		$qid = request()->qid;
		$qanda = QandaModel::where('id',$qid)->first();
		if(!$qanda){
			return ['code'=>0,'msg'=>'该问答不存在'];
		}
		if(QandaGood::where('gid',$gid)->where('qid',$qid)->first()){
			return ['code'=>0,'msg'=>'该问答已添加'];
		}
		DB::beginTransaction();
		try{
			QandaGood::create([
				'gid' => $gid,
				'qid' => $qid,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'添加失败!'];
		}
		$good = ShopGoodModel::where('id',$gid)->first();
		$msg = '商品【'.$good['name'].'】(id:'.$good['id'].')添加问答库';
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'添加成功'];
	}

	public function qanda_update(Request $request){
		$gid = $request->get('gid',null);
		$qid = $request->get('qid',null);

		//商品信息
		$good = ShopGoodModel::where('id',$gid)->first();
		DB::beginTransaction();
		try{
			QandaGood::where('gid',$gid)->delete();
			if(!empty($qid)){
				foreach ($qid as $v) {
					QandaGood::create([
						'gid' => $gid,
						'qid' => $v,
					]);
				}
			}
			DB::commit();
			$msg = '商品【'.$good['name'].'】(id:'.$good['id'].')编辑问答库';
			AdminLogsModel::addLog($msg);
			return returnJson(1,'操作成功');
		}catch(Exception $e){
			DB::rollBack();
			return returnJson(0,'操作失败');
		}
	}

	//编辑商品名称
	public function update_name(){
		$id = request()->id;
		$name = request()->name;
		$good = ShopGoodModel::where('id',$id)->first();
		DB::beginTransaction();
		try{
			ShopGoodModel::where('id',$id)->update(['name'=>$name]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'设置失败'];
		}
		$msg = '商品【'.$good['name'].'】(id:'.$good['id'].'),编辑商品名为:'.$name;
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'设置成功'];
	}

	//删除商品
	public function del_ids(){
		$ids = request()->id;
		DB::beginTransaction();
		try{
			$aa = '';
			foreach($ids as $k=>$v){
				$aa .= $v.',';
				//查询商品信息
				$list = ShopGoodModel::where('id',$v)->first();
				if($list){
					//货源后台的商品
					$store_list = AddShop::where('id',$list['gid'])->first();
					if($store_list){
						AddShop::where('id',$list['gid'])->update(['status'=>4]);
					}
					//删除商品
					ShopGoodModel::where('id', $v)->update(['state' => 3]);
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'删除失败'];
		}
		$msg = 'APP后台删除商品,id:['.$aa.']';
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'删除成功'];

	}

	//素材问答加载页
	public function source_add_qanda(Request $request){
		$id = $request->id;
		return view('admin.qanda.add',compact('request','id'));
	}

	//素材库添加
	public function source_insert_qanda(){
		$id = request()->id;
		$question = request()->question;
		$answer = request()->answer;
		if(empty($question)){
			return ['code'=>0,'msg'=>'请输入问题'];
		}
		if(empty($answer)){
			return ['code'=>0,'msg'=>'请输入答案'];
		}
		//商品信息
		$good = ShopGoodModel::where('id',$id)->first();
		DB::beginTransaction();
		try{
//			if(QandaModel::where('question',$question)->first()){
//				return ['code'=>0,'msg'=>'该问答已存在'];
//			}
			//添加问题
			$qanda = QandaModel::create([
				'question' => $question,
				'answer' => $answer,
			]);

			//商品问答关联
			QandaGood::create([
				'gid' => $id,
				'qid' => $qanda->id,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		$msg = '商品【'.$good['name'].'】(id:'.$good['id'].')添加问答,ID:'.$qanda->id;
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'添加成功','data'=>$qanda];
	}

	//子商品列表
	public function son_list(Request $request){
//		$list = SkuModel::where(function($query){
//			if(request()->keywords){
//				$query->where('gid',request()->keywords);
//			}
//		})->paginate(15);

		$keywords = request()->keywords;
		$state = request()->state;
		$num = request()->num;
		$g_state = request()->g_state;
		$list = SkuModel::from('shop_good_sku as s')
			->leftjoin('shop_good as g','s.gid','=','g.id')
			->select('s.*','g.name as gname')
			->when($keywords, function ($query) use ($keywords) {
				return $query->where('g.id',request()->keywords);
			})
			->when($state,function($query) use ($state){
				if($state == 1){
					return $query->whereNull('s.picname');
				}
			})
			->when($num,function($query) use ($num){
				if($num == 1){
					return $query->where('sum',0);
				}else{
					return $query->where('sum','<>',0);
				}
			})
			->when($g_state,function($query) use ($g_state){
				if($g_state == 1){
					return $query->where('g.state',3);
				}
			})

			->orderBy(DB::raw('convert(`g`.`name` using gbk)'))
			->orderBy('s.id','asc')
			->where('s.state',1)
			->paginate(15);

		foreach($list as $k=>$v){
			if($v['oss_pic']){
				$v['picname'] = $v['oss_pic'];
			}
			$list[$k]['gname'] = ShopGoodModel::where('id',$v['gid'])->value('name');
		}
		$pageParam['keywords'] = request()->keywords;
		$pageParam['page'] = request()->pages;
		$pageParam['state'] = request()->state;
		$pageParam['num'] = request()->num;
		$pageParam['g_state'] = request()->g_state;
		$pages = $request->input('page',1);
		//分页
		$page = $list->appends($pageParam)->links();
		return view('admin.sgood.index',compact('list','pages','request','page'));
	}

	//编辑子商品的货源ID
	public function son_update_id(){
		$id = request()->id;
		//货源ID
		$store_id = request()->store_id;
		//商品信息
		$sku_list = SkuModel::where('id',$id)->first();
		//商品信息
		$good = ShopGoodModel::where('id',$sku_list['gid'])->first();
		if(empty($sku_list)){
			return ['code'=>0,'msg'=>'该商品不存在'];
		}
		//货源商品信息
		$store_list = AddShop::where('id',$store_id)->first();
		if(empty($store_list)){
			return ['code'=>0,'msg'=>'该货源商品不存在'];
		}
		//编辑子商品的货源ID
		DB::beginTransaction();
		try{
			SkuModel::where('id',$id)->update(['store_id'=>$store_id]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>"操作失败"];
		}
		$msg = '商品【'.$good['name'].'】(id:'.$good['id'].')- 规格【'.$sku_list['attr'].'】,编辑货源ID:'.$store_id;
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'操作成功'];
	}

	//删除规格商品
	public function son_delete(){
		$id = request()->id;
		$list = SkuModel::where('id',$id)->first();
		if(empty($list)){
			return ['code'=>0,'msg'=>'商品信息有误'];
		}
		//商品信息
		$good = ShopGoodModel::where('id',$list['gid'])->first();
		DB::beginTransaction();
		try{
			SkuModel::where('id',$id)->delete();
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'删除失败'];
		}
		$msg = '商品【'.$good['name'].'】(id:'.$good['id'].'),删除规格【'.$list['attr'].'】(规格id:'.$id.')';
		AdminLogsModel::addLog($msg);
		return ['code'=>1,'msg'=>'删除成功'];
	}

	//添加视频
	public function source_add_vedio(Request $request){
		$id = request()->id;
		return view('admin.shop.source_vedio', compact('id','request'));
	}
}
